package com.neusoft.thread11queue;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * 生产者和消费者模式
 * @author Zhang.Yan
 *
 */
public class BlockQueueTest
{
	/**
	 * 装鸡蛋的盘子，5个
	 */
	private BlockingQueue<Object> plate=new ArrayBlockingQueue<>(5);
	/**
	 * 放入鸡蛋
	 * @param egg
	 */
	public void putEgg(Object egg)
	{
		try
		{
			plate.put(egg);
			System.out.println("放入鸡蛋,鸡蛋总量："+plate.size());
		}
		catch (InterruptedException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 拿走鸡蛋
	 * @return
	 */
	public Object getEgg()
	{
		try
		{
			System.out.println("拿走鸡蛋,鸡蛋总量："+plate.size());
			return plate.take();
		}
		catch (InterruptedException e)
		{
			e.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args)
	{
		BlockQueueTest plate=new BlockQueueTest();
		
		for(int i=0;i<10;i++)
		{
			new Thread(new PutEggThread(plate)).start();
		}
		for(int i=0;i<10;i++)
		{
			new Thread(new TakeEggThread(plate)).start();
		}
	}
	
}


class PutEggThread implements Runnable
{
	BlockQueueTest plate;
	
	public PutEggThread(BlockQueueTest plate)
	{
		this.plate=plate;
	}

	@Override
	public void run()
	{
		plate.putEgg(new Object());
		
	}
}


class TakeEggThread implements Runnable
{
	BlockQueueTest plate;
	
	public TakeEggThread(BlockQueueTest plate)
	{
		this.plate=plate;
	}

	@Override
	public void run()
	{
		
		plate.getEgg();
	}
}